<template>
     <div class="rightBoxContainer">
          <div class="titleBox">
               <span v-if="chartData?.province">
                    {{ chartData?.province + ' ' + chartData?.city + ' ' + chartData?.conty + ' ' + chartData?.village }}
               </span>
               <span v-else>请选择行政区划</span>
          </div>
          <div class="searchBox">
               <page-search
                    pageName="pages_container"
                    v-if="searchFormConfigRef"
                    ref="pageSearchRef"
                    :searchConfig="searchFormConfigRef"
                    @queryBtnClick="handleQueryClick"
                    @resetBtnClick="handleResetClick"
                    @searchChange="searchChange">
                    <template #button>
                         <!-- <el-button @click="handleNewData()">新增</el-button> -->
                    </template>
               </page-search>
          </div>
          <div class="tableBox">
               <page-content
                    v-if="contentTableConfigRef"
                    ref="pageContentRef"
                    :tableLoading="tableLoading"
                    pageName="pages_container"
                    :contentConfig="contentTableConfigRef"
                    @getTableList="getTableList"
                    @getSelectionData="getSelectionData"
                    :showHandle="true">
                    <template #btns>
                         <el-button @click="handleNewData()" type="primary">新增</el-button>
                    </template>
                    <template #meetingPhoto="scoped">
                         <uploadBtn
                              :otherData="scoped.row"
                              @onSuccess="handleUploadClick"
                              text=""
                              type="warning"
                              size="small"
                              :fileType="['.png', '.jpg', '.jpeg', '.gif', '.bmp']">
                              <el-icon class="iconfont icon-shangchuan"></el-icon>
                         </uploadBtn>
                    </template>
                    <template #picturepath="scoped">
                         <el-image
                              v-if="scoped.row.picturepath"
                              style="width: 100px; height: 30px"
                              :src="urlFun(scoped.row.picturepath)"
                              :zoom-rate="1.2"
                              :max-scale="7"
                              :min-scale="0.2"
                              preview-teleported
                              :preview-src-list="[urlFun(scoped.row.picturepath)]"
                              fit="cover" />
                    </template>
                    <template #operation="scoped">
                         <span title="编辑" v-show="scoped.row.username == userStoreInstance.username">
                              <el-button type="warning" @click="handleEditData(scoped.row)" size="small" style="cursor: pointer; margin-right: 5px">
                                   <el-icon class="iconfont icon-bianji"></el-icon>
                              </el-button>
                         </span>
                         <span title="删除" v-show="scoped.row.username == userStoreInstance.username">
                              <el-popconfirm
                                   title="此操作将永久删除,是否继续?"
                                   cancel-button-type="info"
                                   @confirm="handleDelData(scoped.row)"
                                   confirm-button-text="确定"
                                   cancel-button-text="取消">
                                   <template #reference>
                                        <span title="删除">
                                             <el-button type="danger" size="small">
                                                  <el-icon style="cursor: pointer" class="iconfont icon-shanchu"></el-icon>
                                             </el-button>
                                        </span>
                                   </template>
                              </el-popconfirm>
                         </span>
                    </template>
                    <template #starttime="scoped">
                         {{ scoped.row.starttime ? formatDate(scoped.row.starttime) : '-' }}
                    </template>
                    <template #endtime="scoped">
                         {{ scoped.row.endtime ? formatDate(scoped.row.endtime) : '-' }}
                    </template>
               </page-content>
          </div>
          <page-modal
               v-if="modalConfigRef && modalConfigRefShow"
               ref="pageModalRef"
               :modalConfig="modalConfigRef"
               :defaultInfo="modalInfo"
               pageName="pages_container"
               @addSuccess="addSuccess"
               @editSuccess="editSuccess"></page-modal>
     </div>
</template>

<script setup lang="ts">
import uploadBtn from '@/components/uploadBtn/index.vue'
import pageContent from '@/components/pageContent'
import pageSearch from '@/components/pageSearch'
import pageModal from '@/components/pageModal'
import { usePageTable } from '@/hooks/table/usePageTable'
import { contentTableConfig, emptyTableConfig } from './config/content.config'
import { searchFormConfig } from './config/search.config'
import { modalConfig } from './config/modal.config'
import { GetMeetPc, AddMeet, UpdateMeet, DeleteMeet, UploadMeetImage } from '@/api/meetRecords'
import { GetDistrictsByLevelAndName } from '@/api/common'
import { ElMessage } from 'element-plus'
import userStore from '@/store/modules/user'
import { formatDate, parseMileage } from '@/utils/formtFun'

const userStoreInstance = userStore()
let props = defineProps({
     chartData: {
          type: Object as PropType<any>,
     },
})

const modalConfigRefShow = ref(true)
const editHandleCallback = async (val: any) => {
     let district = [val.province, val.city, val.conty, val.village]
     // 从后往前循环判断 省市县镇是否为空
     for (let i = district.length - 1; i >= 0; i--) {
          if (district[i]) {
               break
          }
          district.pop()
     }
     modalInfo.value = {
          ...val,
          district: district[district.length - 1] ?? '',
     }
     modalConfigRefShow.value = false
     nextTick(() => {
          modalConfigRefShow.value = true
     })
     modalConfigRefShow.value = true
}
// 单个删除方法回调
const delHandleCallback = async (val: any) => {
     try {
          let obj = {
               id: val ?? modalInfo.value.id,
          }
          const res: any = await DeleteMeet(obj)
          const message = res == '删除成功' ? '删除成功' : '删除失败'
          ElMessage({
               type: res == '删除成功' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
const {
     searchFormConfigRef,
     contentTableConfigRef,
     modalConfigRef,
     pageModalRef,
     pageContentRef,
     pageSearchRef,
     modalInfo,
     tableLoading,
     selectCheckData,
     permissionRef,
     handleOnSuccess,
     handleNewData,
     handleEditData,
     handleDelData,
     handleQueryClick,
     handleResetClick,
     getSelectionData,
     templateDownloadClick,
     hasPermission,
} = usePageTable(null, editHandleCallback, null, delHandleCallback)
onMounted(async () => {
     await getSelectOptions()
     contentTableConfigRef.value = contentTableConfig
     searchFormConfigRef.value = searchFormConfig
     modalConfigRef.value = modalConfig
     nextTick(() => {
          pageSearchRef.value?.handleResetClick()
     })
})
const urlFun = (url: any) => {
     // 获取当前环境变量
     const env = import.meta.env.VITE_SERVE
     return url ? env + url?.split('~')[1] : ''
}
const searchChange = (data: any) => {
     console.log('searchChange', data)
}

const getTableList = async (params: any) => {
     try {
          const requestParams = {
               ...params,
               ...props.chartData,
               starttime: params.starttime ? params.starttime + ' 00:00:00' : '',
               endtime: params.endtime ? params.endtime + ' 23:59:59' : '',
          }
          tableLoading.value = true
          const tabelData: any = await GetMeetPc(requestParams)
          tableLoading.value = false
          const newData = tabelData.Data || []
          const newTotal = Number(tabelData.Count) || 0

          nextTick(() => {
               if (newData.length > 0) {
                    pageContentRef.value!.setTableData(newData, newTotal)
               } else {
                    pageContentRef.value!.setTableData([], 0)
               }
          })
     } catch (error) {
          tableLoading.value = false
          console.error('Failed to get table data:', error)
     }
}

const findPathToNode = (tree: any[], targetLabel: string, currentPath: any[] = []): any[] | null => {
     for (const node of tree) {
          if (!node.Name) {
               continue // 跳过空标签的节点
          }
          const newPath = [...currentPath, node]
          if (node.Name === targetLabel) {
               return newPath
          }
          if (node.SubDistricts && node.SubDistricts.length > 0) {
               const result = findPathToNode(node.SubDistricts, targetLabel, newPath)
               if (result) {
                    return result
               }
          }
     }
     return null
}
const dislevel = ref('')
const formatAddAndEditData = (data: any) => {
     let activeData = Array.isArray(data.district) ? data.district[data.district.length - 1] : data.district
     let path: any = findPathToNode(districtList.value, activeData)
     dislevel.value = path[path.length - 1].Unit ?? ''
     let district = {
          province: '',
          city: '',
          conty: '',
          village: '',
     }
     if (path) {
          path.forEach((node: any) => {
               switch (node.Unit) {
                    case '省':
                         district.province = node.Name
                         break
                    case '市':
                         district.city = node.Name
                         break
                    case '县':
                         district.conty = node.Name
                         break
                    case '乡':
                         district.village = node.Name
                         break
                    default:
                         break
               }
          })
     }
     return {
          ...data,
          ...district,
     }
}
const handleUploadClick = async (data: any) => {
     console.log(data)
     try {
          let obj = {
               id: data.otherData.id,
               userid: userStoreInstance.userInfoData.userid,
          }
          const res: any = await UploadMeetImage(obj, [data.file])
          const message = res == '上传成功！' ? '上传成功' : '上传失败'
          ElMessage({
               type: res == '上传成功！' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
// 新增的回调方法
const addSuccess = async (val: any) => {
     try {
          let obj = {
               ...formatAddAndEditData(val),
               dislevel: dislevel.value,
          }
          const res: any = await AddMeet(obj)
          const message = res == '添加成功' ? '添加成功' : '添加失败'
          ElMessage({
               type: res == '添加成功' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}

// 编辑的回调方法
const editSuccess = async (val: any) => {
     try {
          let obj = {
               ...formatAddAndEditData(val),
               dislevel: dislevel.value,
          }
          const res: any = await UpdateMeet(obj)
          const message = res == '修改成功' ? '编辑成功' : '编辑失败'
          ElMessage({
               type: res == '修改成功' ? 'success' : 'error',
               message,
          })
          pageSearchRef.value?.handleQueryClick()
     } catch (error) {
          console.log(error)
     }
}
const districtList = ref([])
// 获取对应选择器的下拉选项
const getSelectOptions = async () => {
     try {
          const res = await GetDistrictsByLevelAndName()

          modalConfig.formItems.forEach((item: any) => {
               if (item.field === 'district') {
                    item.cascader = Array.isArray(res) ? res : []
                    districtList.value = item.cascader
               }
          })
     } catch (error) {
          console.error(error)
     }
}
watch(
     () => props.chartData,
     () => {
          pageSearchRef.value?.handleQueryClick()
     },
     { deep: true },
)
</script>

<style lang="scss" scoped>
.rightBoxContainer {
     width: 100%;
     height: 100%;
     display: flex;
     flex-direction: column;
     overflow: auto;
     padding-right: 5px;

     .titleBox {
          width: 100%;
          height: 5%;
          color: #fff;
          font-weight: bold;
          font-size: 18px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #0a3e6e;
          border-radius: 5px;
     }

     .searchBox {
          width: 100%;
          height: auto;
     }

     .tableBox {
          height: 80%;
          width: 100%;
          border-radius: 10px;
     }
}
</style>
